/*
Copyright 2011 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.catonine.fontchooser.impl;

import java.awt.Font;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;

import nu.zoom.catonine.fontchooser.FontChooser;
import nu.zoom.ui.Resources;
import nu.zoom.ui.Resources.ResourceNotFoundException;

/**
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 * 
 */
public final class FontChooserImpl implements FontChooser {
	private static final long serialVersionUID = 7797903502133711247L;
	private final Resources resources;
	private FontChooserPanel gui = null;
	private ArrayList<FontValuesListener> listeners = new ArrayList<FontChooser.FontValuesListener>();

	public FontChooserImpl(final Resources resources) {
		this.resources = resources;
	}

	@Override
	public boolean isChanged() {
		if (this.gui == null) {
			return false;
		}
		return gui.isChanged();
	}

	@Override
	public void resetChangeStatus() {
		if (this.gui != null) {
			this.gui.resetChangeStatus();
		}
	}

	@Override
	public synchronized void addFontValuesListener(FontValuesListener listener) {
		if (!this.listeners.contains(listener)) {
			this.listeners.add(listener);
		}
	}

	@Override
	public synchronized void removeFontValuesListener(FontValuesListener listener) {
		this.listeners.remove(listener);
	}

	@Override
	public Font getCurrentFontValues() {
		return (this.gui == null) ? null : this.gui.getCurrentFontValues();
	}

	@Override
	public JComponent getFontChooserGUI(final Font startFont, final Font defaultFont) throws ResourceNotFoundException {
		if (gui == null) {
			buildGUI(startFont, defaultFont);
		}
		return gui;
	}

	private void buildGUI(final Font startFont, final Font defaultFont) throws ResourceNotFoundException {
		gui = new FontChooserPanel(resources, this, startFont, defaultFont);
		gui.initGUI();
	}

	private synchronized List<FontValuesListener> copyListeners() {
		ArrayList<FontValuesListener> copy = new ArrayList<FontChooser.FontValuesListener>(this.listeners);
		return copy;
	}

	void fireFontChanged(final Font font) {
		List<FontValuesListener> copyListeners = copyListeners();
		for (final FontValuesListener fontValuesListener : copyListeners) {
			fontValuesListener.fontValuesChanged(this, font);

		}
	}

}
